package com.rizhov.main;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ClientHandler extends Thread {

    protected int id;
    protected Socket clientSocket;

    public ClientHandler(int currentId, Socket acceptedSocket) {
	clientSocket = acceptedSocket;
	id = currentId;

	setPriority(NORM_PRIORITY);
	start();
    }

    @Override
    public void run() {
	try {
	    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(
		    clientSocket.getOutputStream()));
	    oos.flush();
	    ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
	    while (true) {
		ArrayList<Object> arrList = null;
		try {
		    arrList = ((ArrayList<Object>) ois.readObject());
		} catch (ClassNotFoundException e) {
		    e.printStackTrace();
		}
		int command = (Integer) arrList.get(0);
		if (command == CommandDescriptor.ADD_STRING.getCode()) {
		    String tempStr = (String) arrList.get(1);
		    boolean result = Server.colleciton.add(tempStr);
		    if (result) {
			oos.writeInt(1);
			oos.flush();
		    } else {
			oos.writeInt(0);
			oos.flush();
		    }
		} else if (command == CommandDescriptor.REMOVE_STRING.getCode()) {
		    String tempStr = (String) arrList.get(1);
		    boolean result = Server.colleciton.remove(tempStr);
		    if (result) {
			oos.writeInt(1);
			oos.flush();
		    } else {
			oos.writeInt(0);
			oos.flush();
		    }
		} else if (command == CommandDescriptor.GET_SIZE_OF_COLLECTION.getCode()) {
		    oos.writeInt(Server.colleciton.size());
		    oos.flush();
		} else if (command == CommandDescriptor.GET_BY_INDEX.getCode()) {
		    int index = (Integer) arrList.get(1);
		    String result = null;
		    try {
			result = Server.colleciton.get(index);
		    } catch (IndexOutOfBoundsException e) {

		    }
		    if (result != null) {
			oos.writeObject(result);
			oos.flush();
		    } else {
			oos.writeObject("null");
			oos.flush();
		    }
		} else if (command == CommandDescriptor.CLOSE_THREAD.getCode()) {
		    break;
		} else if (command == CommandDescriptor.GET_ALL_THE_LIST.getCode()) {
		    List<String> tempList = null;
		    try {
			tempList = Server.colleciton.subList(0, Server.colleciton.size());
		    } catch (IndexOutOfBoundsException e) {

		    }
		    if (tempList != null && tempList.size() != 0) {
			tempList = new ArrayList<String>(tempList);
			oos.writeObject(tempList);
			oos.flush();
		    } else {
			oos.writeObject("null");
			oos.flush();
		    }
		}
	    }
	    oos.close();
	    ois.close();
	} catch (IOException e) {
	    e.printStackTrace();
	}

    }
}
